package org.linlinjava.litemall.wx.web;

import com.github.pagehelper.PageInfo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallCreditHistory;
import org.linlinjava.litemall.db.domain.LitemallUser;
import org.linlinjava.litemall.db.service.LitemallCreditHistoryService;
import org.linlinjava.litemall.db.service.LitemallUserService;
import org.linlinjava.litemall.wx.annotation.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: renshuai
 * @date: 2019/3/1 11:08
 * @Description:
 */
@RestController
@RequestMapping("/wx/creditHistory")
@Validated
public class WxCreditHistoryController {

    private final Log logger = LogFactory.getLog(WxCreditHistoryController.class);

    @Autowired
    private LitemallCreditHistoryService creditHistoryService;

    @Autowired
    private LitemallUserService userService;

    /**
     * 历史积分列表
     *
     * @param page 分页页数
     * @param size 分页大小
     * @return 用户足迹列表
     */
    @GetMapping("list")
    public Object list(@LoginUser Integer userId,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer size) {
        if (userId == null) {
            return ResponseUtil.unlogin();

        }
        List<LitemallCreditHistory> creditHistories = creditHistoryService.listByUserId(userId, page, size, "time", "desc");
        long count = PageInfo.of(creditHistories).getTotal();
        int totalPages = (int) Math.ceil((double) count / size);
        Map<String, Object> result = new HashMap<>();
        result.put("footprintList", creditHistories);
        result.put("totalPages", totalPages);
        return ResponseUtil.ok(result);
    }

    @GetMapping("transfer")
    public Object transfer(@LoginUser Integer userId, @RequestParam Integer transferUserId, @RequestParam BigDecimal credit) {
        if (userId == null) {
            return ResponseUtil.unlogin();

        }
        LitemallUser user = userService.findById(userId);
        if (credit.compareTo(user.getCredit()) > 0) {
            return ResponseUtil.fail(510, "积分不足");
        }
        int count = creditHistoryService.transfer(userId, transferUserId, credit);
        if (count != 1) {
            return ResponseUtil.fail(520, "系统出错...");
        }
        return ResponseUtil.ok();
    }
}
